﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Flame.Socket
{
    public class AutoItSocket
    {
        public const int Waiting = 100;
        //int _port = 8000;
        //string _hostName = "127.0.0.1";
        string _result = null;
        int id = 0;

        AutoIt _autoit;
        TcpServer_ _socket;
        public AutoItSocket(string exePath, string hostName = "127.0.0.1", int port = 8000)
        {
            _autoit = new AutoIt(exePath);
            _socket = new TcpServer_(hostName, port);

            string script = String.Format(@"
TCPStartup()
$ConnectedSocket = TCPConnect(""{0}"", {1}) 
Func l($s)
	TCPSend($ConnectedSocket, StringToBinary(""11"" & $s, 4))
	sleep({2});
EndFunc  
Func x()
	TCPSend($ConnectedSocket, ""00"")
	Exit
EndFunc 
Func get($name)
	TCPSend($ConnectedSocket, ""20"" & $name)
	sleep({2});
EndFunc 
Func set()
	TCPSend($ConnectedSocket, ""21"")
	sleep({2});
EndFunc 
While 1
	$recv = TCPRecv($ConnectedSocket, 4, 1)
	if not $recv = 0 Then
		$s = BinaryToString(TCPRecv($ConnectedSocket, $recv, 1))
		
	EndIf
WEnd", hostName, port, Waiting);

            _socket.Start();

            while (_socket.StatusServer != StatusServer.WaitingForClient) { }
            _autoit.Start(script);
            while (_socket.StatusServer == StatusServer.WaitingForClient) { }
        }

        public void Close()
        {
            Execute("x()");
            _socket.Close();
        }

        public string Execute(string script)
        {
            _result = null;
            id++;
            _socket.OnMessage += new EventHandler<TcpServer_.MessageEventArgs>(_socket_OnMessage);
            _socket.Send(new TcpServer_.Message() { Id = id, Script = script });
            while (_result == null) { }
            return _result;
        }

        void _socket_OnMessage(object sender, TcpServer_.MessageEventArgs e)
        {
            if (e.Message.Id == id)
                _result = e.Result.Data;
        }
    }
}
